package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.kly.enums.ParameterTypeEnum;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.IssueUserBackConfigEntity;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.db.entity.UserWlmEntity;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.LikeEnum;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.msgClient.MsgAPI;
import com.kly.user.service.AsyncSendMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 老用户召回
 */
@Component
public class IssueUserBackTask {

    private static Log logger = LogFactory.getLog(IssueUserBackTask.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private IssueUserBackConfigDao issueUserBackConfigDao;

    @Resource
    UserWlmDao userWlmDao;

    @Resource
    UserWlmLogDao userWlmLogDao;

    @Resource
    AsyncEventBus pushEventBus;

    @Resource
    private AsyncSendMsgService asyncSendMsgService;

    @Resource
    private UserGreetingCommonContentDao userGreetingCommonContentDao;

    @Resource
    MsgAPI msgAPI;

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();

    @Scheduled(fixedDelay = 60000 * 20)
    public void execute() {

        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        Calendar calendar = Calendar.getInstance();
        int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
        List<IssueUserBackConfigEntity> issueUserBackConfigEntityList = issueUserBackConfigDao.getCurrentDayConfig(weekDay);
        if (!issueUserBackConfigEntityList.isEmpty()) {
            List<IssueUserBackConfigEntity> issueUserBackConfigEntities = issueUserBackConfigEntityList.stream().filter(o -> LocalTime.now().isAfter(o.getBeginTime()) && o.getEndTime().isAfter(LocalTime.now())).collect(Collectors.toList());
            if (!issueUserBackConfigEntities.isEmpty()) {
                calendar.add(Calendar.DATE, -20);
                Date date = calendar.getTime();
                int count = userDao.getRegisterDateUserCount(String.valueOf(date.getTime()));
                if (count > 0) {
                    int pageSize = (count / 100) + 1;
                    for (int i = 0; i < pageSize; i++) {
                        List<UserEntity> userEntityList = userDao.getRegisterDateUserLimit(String.valueOf(date.getTime()), i);
                        for (UserEntity userEntity : userEntityList) {
                            dealCondition(userEntity, issueUserBackConfigEntities.get(0));
                        }
                        if (userEntityList.size() != 100) {
                            break;
                        }
                    }
                }
            }
        }
    }

    private void dealCondition(UserEntity userEntity, IssueUserBackConfigEntity issueUserBackConfigEntity) {
        logger.info("=====IssueUserBackTask 用户召回, userCode:{}", userEntity.getUserCode());
        // TODO: 2024/6/14 在线的走wlm流量控制，不在线的走用户召回逻辑
        if (issueUserBackConfigEntity.getMessageType() == 1) {
            //wlm
            //读取
            UserEntity user = userDao.queryWLMRecommendUsers(userEntity.getUserCode(), userEntity.getLookingFor(), 1);
            if (user != null) {
                addUserWlm(userEntity.getUserCode(), user.getUserCode());
                msgAPI.sendBackMessage(AppEnum.MEBOO, userEntity.getUserCode(), "You Got New Like！\uD83D\uDC98", "Click to see who this adorable little one is \uD83D\uDC40");
                logger.info("IssueUserBackTask 1 :" + userEntity.getUserCode());
            }
        } else {
            //推送语
            List<String> messageList = userGreetingCommonContentDao.getGreetingContent("122", 1, userEntity.getAppCode());
            if(!messageList.isEmpty()) {
                msgAPI.sendBackMessage(AppEnum.MEBOO, userEntity.getUserCode(), "Meboo \uD83D\uDC96\n", messageList.get(0));
            }
        }
    }


    private void addUserWlm(String userCode, String userCodeFriend) {
        UserWlmEntity userWlmEntity = new UserWlmEntity();
        userWlmEntity.setUserCode(userCodeFriend);
        userWlmEntity.setUserCodeWlm(userCode);
        userWlmEntity.setWlmType(LikeEnum.LIKE.getType());
        userWlmEntity.setSendWlmTime(new Date());
        userWlmDao.insert(userWlmEntity);
        userWlmLogDao.addWlmLog(userWlmEntity);
        // 推送消息
        pushMessage(userCodeFriend, userCode, AppEnum.MEBOO);
    }


    private void pushMessage(String fromUseCode, String toUserCode, AppEnum appEnum) {
        pushEventBus.post(buildEvent(fromUseCode, toUserCode, appEnum));
    }

    private Event buildEvent(String fromUseCode, String toUserCode, AppEnum appEnum) {
        Map<String, Integer> params = Maps.newHashMap();
        params.put("type", ParameterTypeEnum.WHO_LIKE_ME.getId());
        return Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).fromUserCode(fromUseCode).toUserCode(toUserCode).app(appEnum).content(JSONObject.toJSONString(params)).build();
    }
}
